/**
 * 数据库表格动态展示
 */

mini.parse();
var grid = new mini.DataGrid();
var tree;
var cols;
var grid_data;

var cTableName;

var formItem = parent.getFormItem().item;//菜单跳转后获取数据
console.log(formItem,'formItem');
var menusFormTypes =  formItem.menusFormTypes;//表单/档案
var textField;
var complex_add_field;//复杂档案保存时增加的字段名称
var formId = formItem.formListId;
var menuId = formItem.id.match(/menuId(\S*)/)[1];
var treeSelected;
var nodes;//所选节点的所有父节点
var condition;
// console.log(formId,'formId');
//$('.table_name').html('<b>'+ formItem.formName +'</b>');//表名
// localStorage.clear();
// localStorage.removeItem("formShow");


init();
parent.activeChanged();//更新表格页

function init() {
	//请求数据列表类型
	$.ajax({
		url : ajaxUrl + '/formList/findByFormId.do',
		type: "post",
        dataType: "json",
        data: {
            formListId: formId,
        },
        success: function (data){
        	console.log(data);
        	var type = data.data.formTypes;
        	menusFormTypes = type;
        	
        	$("#gridField").css({
        		height : document.body.clientHeight - 40
        	});

            //加载列
            $.ajax({
                url: ajaxUrl + "/formltems/findByFormListIdToStyle.do",
                type: "post",
                dataType: "json",
                data: {
                    formListId: formId,
                    menuId: menuId
                },
                success: function(data){
                    //console.log(data,'列');
                    for(var i=0;i<data.length;i++) {
                        if(data[i].tableType !='table' && data[i].tableType !='tab_table' && data[i].tableType !='tab' && data[i].tableType !='formname') {
                            cTableName = data[i].tableName;//获得主表名
                        }
                        if(i == 1) {
                            complex_add_field = data[i].cTreeStruct;
                        }
                    }
                    cols = data;//列数据
                    //cols.push(cols[cols.length-1])
                    console.log(cols,'列赋值数据');
                    grid.set({
                        url: "",
                        style: "width:100%;height:100%;",
                        id: "datagrid",
                        columns: cols,
                        multiSelect: true,
                        allowResize: true,
                        allowCellEdit: false,
                        allowCellSelect: true,
                        cellEditAction: "cellclick",
                        allowRowSelect: true,
                        showPager: false,
                        editNextOnEnterKey: true,
                        editNextRowCell: true
                    });
                    grid.render(document.getElementById("gridField"));

                    loadGrid();
                    initBtn();
                },
                error : function(data){
                }
            });
        	
        },
        error: function (data){
        	console.log('失败');
        }
	})


}

function loadGrid() {
	
    console.log(menusFormTypes,'档案类型')
    //复杂档案
    if(menusFormTypes == 'complex') {
        tree = mini.get("tree");
        //加载树形
        $.ajax({
            url: ajaxUrl + "/formltems/formTree.do?",
//        	url: "http://192.168.31.65:8080/bpm/formltems/formTree.do?",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId
            },
            success: function(treeData){
                console.log(treeData,'treeData');
                $.ajax({
                    url: ajaxUrl + "/formList/findByFormListId.do?formListId="+formId,
                    type: "post",
                    dataType: "json",
                    success: function(textFieldData){
                        textField = $.parseJSON(textFieldData.data).selecteds[0].cTableField;
//                        condition = $.parseJSON(textFieldData.data).selecteds[0].cTableName;
                        console.log(textField,'树形textField');
                        tree.set({
                            textField: 'name'
                        });
//                        tree.loadList(treeData, "id", "parent_level");
//                        console.log(tree.getData());
                        tree.setData(treeData);
                        var clickNodeFlag = 0;
                        tree.on("nodeselect", function (e) {
                            console.log(e);
                            clickNodeFlag++;
                            treeSelected = e.selected;
                            nodes = tree.getAncestors(treeSelected);
                            nodes.push(treeSelected);
                            $.ajax({
                                url: ajaxUrl + "/formltems/selectArchives.do",
//                                url:"http://192.168.31.65:8080/bpm/formltems/selectArchives.do",
                                type: "post",
                                dataType: "json",
                                data: {
                                    formListId: formId,
                                    condition: e.node.tabName,
                                    conValue: e.node.id
                                },
                                success: function(data){
                                    console.log(data);
                                    grid_data = data.data;
                                    grid.setData(grid_data);
                                },
                                error : function(data){
                                }
                            });
                        })
                    },error : function(data){
                    }
                });
            },
            error : function(data){
            }
        });

    }else if(menusFormTypes == 'treeFile'){
    	$.ajax({
    		url: ajaxUrl + "/formList/findByFormListId.do?formListId="+formId,
    		type: "post",
            dataType: "json",
            success: function(data){
            	console.log(data);
            },
            error: function(data){
            	console.log('失败');
            }
    	})
    }else {
        //$(".left").css({width: 0});
    	$(".left").css({display: 'none'});
        $(".right").css("cssText", "width: 100% !important;overflow:auto;");
        //数据
        $.ajax({
            url: ajaxUrl + "/sqlAction/findAll.do",
//            url:"http://192.168.31.65:8080/bpm/formltems/findFormSource.do",
            type: "post",
            dataType: "json",
            data: {
                formListId: formId,
                menuId: menuId
            },
            success: function (data) {
                console.log(data, '数据');
                grid_data = data;
                grid.setData(grid_data);
            },
            error: function (data) {
            }
        });
    }
}


var formShow;
//新增 跳转到表单展示页
function addFormShow() {
    formShow = {
        action: 'add',
        formListId: formId,
        cTableName: cTableName,
        menuId: menuId,
        edit_data: [],
        menusFormTypes: menusFormTypes,
        treeSelected: treeSelected,
        textField: textField,
        complex_add_field: complex_add_field,
        nodes: nodes
    };
    console.log(formShow);
    // document.cookie='';
    // document.cookie= "items="+JSON.stringify(formShow)+";path=/";
    // localStorage.clear();
    // localStorage.removeItem("formShow");
    localStorage.setItem("formShow",JSON.stringify(formShow));

    var item = {
        iconCls: "fa fa-desktop",
        // id: formId,
        text: "表单展示",
        url: "../pages/formDesign/formTemplate2.html"
    };
    parent.activeTab(item);//与父页面通信
}

//编辑 跳转到表单展示页
function editFormShow() {
    var row = grid.getSelecteds();
    if (row.length > 1) {
        mini.alert('不能对多条数据进行编辑');
    } else if (row.length == 0) {
        mini.alert('请选择需要编辑的行');
    } else {
        console.log(row[0], '编辑');
        var obj = {};
        if(row[0].mTableId == undefined) {
            obj = {
                cTableName: cTableName,// 主表的名称
                formId: formId,// 表单id
                mTableId: row[0].id  //列的id
            }
        }else {
            obj = {
                cTableName: cTableName,// 主表的名称
                formId: formId,// 表单id
                mTableId: row[0].mTableId  //列的id
            }
        }

        $.ajax({
            url: ajaxUrl + "/formltems/formByMtableId.do",
            type: "POST",
            data: {
               obj: JSON.stringify(obj)
            },
            success: function (data) {
                console.log(data, '获得编辑的数据');
                formShow = {//表单展示页
                    action: 'edit',
                    formListId: formId,
                    cTableName: cTableName,
                    menuId: menuId,
                    edit_data: data[0],
                    treeSelected: treeSelected,
                    textField: textField,
                    complex_add_field: complex_add_field
                };
                // document.cookie='';
                // document.cookie= "items="+JSON.stringify(formShow)+";path=/";
                // localStorage.clear();
                // localStorage.removeItem("formShow");
                localStorage.setItem("formShow",JSON.stringify(formShow));
                var item = {
                    iconCls: "fa fa-desktop",
                    // id: formId,
                    text: "表单展示",
                    url: "../pages/formDesign/formTemplate2.html"
                };
                parent.activeTab(item);//与父页面通信
            },
            error: function (data) {
            }
        });
    }
}

//删除行
function removeRow() {

    mini.confirm("确定删除？", "确定？",
        function (action) {
            if (action == "ok") {
                var rows = grid.getSelecteds();
                console.log(rows,'列');
                if (rows.length > 0) {
                    var del_data = [];
                    //为删除的数据添加所属表名
                    for(var i=0;i<rows.length;i++) {
                        for(var item in rows[i]) {
                            for(var j=0;j<cols.length;j++) {
                                if(cols[j].hasOwnProperty("tableName")) {
                                	if(rows[i].mTableId == undefined) {
                                        del_data.push({
                                            cTableName: cols[j].tableName,
                                            mTableId: rows[i].id,
                                            formId: formId
                                        });
                                    }else {
                                        del_data.push({
                                            cTableName: cols[j].tableName,
                                            mTableId: rows[i].mTableId,
                                            formId: formId
                                        });
                                    }
                                }
                            }
                        }
                    }
                    del_data = unique(del_data);//数组去重
                    console.log(del_data);
                    // console.log(JSON.stringify(del_data));

                    $.ajax({
                        url: ajaxUrl + "/formltems/deleteFormSource.do",
                        //url:"http://192.168.31.65:8080/bpm/formltems/deleteFormSource.do",
                        type: "post",
                        dataType: "json",
                        data: {
                            obj: JSON.stringify(del_data)
                        },
                        success: function(data){
                            console.log(data,'数据');
                            refresh();
                            mini.alert('删除成功');
                            // console.log(grid.getData());
                        },
                        error : function(data){
                            mini.alert('删除失败')
                        }
                    });
                }else {
                    mini.alert('请选择需要删除的行');
                }
            }
        }
    );
}

//数组对象去重（去除完全重复的对象）
function unique(arr) {
    var arrResult = [];
    for(var i=0;i<arr.length;i++){
        arr[i] = JSON.stringify(arr[i]);//对象转成字符串的方法
        arrResult.push(arr[i]);//重新填装成一个《字符串》组成的数组
    }
    arr = [];//清空原来的数据
    arrResult = $.unique(arrResult); // 去掉重复的字符串
    for(var j=0;j<arrResult.length;j++){
        arrResult[j] = JSON.parse(arrResult[j]);// 重新给字符串转换成对象
        arr.push(arrResult[j]);//重新填装成一个《对象》组成的数组
    }
    // console.log(arr,'组装后的数组');//看一下组装后的数组
    return arr;
}

function search() {
    var search_key = mini.get("search_key").getValue();
    // grid.load({ key: search_key });
}

function onKeyEnter(e) {
    search();
}

//获取表格数据
function refresh() {
	
	 window.location.reload();
	
    // $.ajax({
    //     url: ajaxUrl + "/formltems/findFormSource.do",
    //     type: "post",
    //     dataType: "json",
    //     data: {
    //         formListId: formId,
    //         menuId: menuId
    //     },
    //     success: function(data){
    //         console.log(data,'数据');
    //         grid_data = data;
    //         grid.setData(grid_data);
    //     },
    //     error : function(data){
    //         mini.alert('获取失败')
    //     }
    // });
}

function initBtn() {

    $.ajax({
        type : 'post',
        url : ajaxUrl+"/buttons/findByState.do",
        //url : "http://192.168.31.65:8080/bpm/buttons/findByState.do",
        dataType : 'json',
        success : function (data) {
            console.log(data,'buttons');
            for(var i=0;i<data.data.length;i++) {
                switch (data.data[i].buttonText) {
                    case '增加':
                        $("#add").css({display:"inline-block"});break;
                    case '修改':
                        $("#edit").css({display:"inline-block"});break;
                    case '删除':
                        $("#remove").css({display:"inline-block"});break;
                    case '提交':
                        $("#submit").css({display:"inline-block"});break;
                }
            }
//            $.ajax({
//                type : 'post',
//                // url : ajaxUrl+"/formltems/printFile.do?formListId="+formId,
//                url : "http://192.168.31.65:8080/bpm/formltems/printFile.do?formListId="+formId,
//                dataType : 'json',
//                success : function (data) {
//                    console.log(data,'printValue');
//                    mini.get('printText').setData(data);
//                },
//                error : function (message) {
//
//                }
//            });
        },
        error : function (message) {

        }
    })

}
//提交
function onSubmit(){
	var row = grid.getSelected();
	console.log(row.state,'被选中要提交的行');
	if(row){
		console.log(row.state,'状态');
		if(row.state == 1){
			mini.alert('不能重复提交');
		}else{
			console.log('能提交');
			$.ajax({
				url : ajaxUrl+"/activitiTaskController/startApply.do",
				data: {
					taskId: row.id,
					formId: formId
				},
				type : 'post',
				success: function(data){
					mini.alert(data.msg);
				},
				error: function(data){
					console.log(data);
				}
			})
		}
	}else{
		mini.alert('请选择需要提交的数据');
	}
}
//打印
function onPrint() {
//	top.location.href="//www.baidu.com";
    mini.get("printText").getSelected();
    var data = {
        fileRout: mini.get("printText").getSelected().fileRout,
        datasource: grid.getSelecteds()
    }
    localStorage.setItem('printData',JSON.stringify(data));
	window.open('../../../../printingH5.html','_blank');
}
//路径前缀
var jumpPageUrl = bootPATH + "../frame/frame1/pages/";  
//查看图标
function onEchart(){
	//得到被选择查看的表
	var row = grid.getSelecteds();
	console.log(row);
	//判断是否勾选数据行
	if(row){
		console.log(cTableName);
		//拼接请求主子表数据的参数
		var obj = {};
        if(row[0].mTableId == undefined) {
            obj = {
                cTableName: cTableName,// 主表的名称
                formId: formId,// 表单id
                mTableId: row[0].id  //列的id
            }
        }else {
            obj = {
                cTableName: cTableName,// 主表的名称
                formId: formId,// 表单id
                mTableId: row[0].mTableId  //列的id
            }
        }	
        //请求主子表数据
		$.ajax({
			 url: ajaxUrl + "/formltems/formByMtableId.do",
			 type: "POST",
			 data: {
				 obj: JSON.stringify(obj)
			 },
			 success: function(data){
				 console.log(data,'需要查看的饼图信息');
				 //判断是饼图
				 if(cTableName == 'pie_excel'){
					 //拼接饼图数据结构的子表数据
					 var pie_list = data[0].pie_list;	
					 //标识列表
					 var pieDistributionList = [];
					 pie_list.forEach((item,index)=>{
						 pieDistributionList.push(item.colum_name);
					 });
					 //饼图内容
					 var pieContent = [];
					 pie_list.forEach((item,index)=>{
						 var obj = {};
						 obj.value = item.colum_data;
						 obj.name = item.colum_name;
						 pieContent.push(obj);
					 });
					 //饼图数据
					 var option = {
						        title: {
						            text: data[0].pie_excel[0].pie_name,
						            subtext: data[0].pie_excel[0].pie_subject,
						            x: 'center'
						        },
						        tooltip: {
						            trigger: 'item',
						            formatter: "{a} <br/>{b} : {c} ({d}%)"
						        },
						        legend: {
						            orient: 'vertical',
						            left: 'left',
						            data: pieDistributionList
						        },
						        series: [
						            {
						                name: '详细信息',
						                type: 'pie',
						                radius: '55%',
						                center: ['50%', '60%'],
						                data: pieContent,
						                itemStyle: {
						                    emphasis: {
						                        shadowBlur: 10,
						                        shadowOffsetX: 0,
						                        shadowColor: 'rgba(0, 0, 0, 0.5)'
						                    }
						                }
						            }
						        ]
						    };
					 function buildChart() {
						    var chart1 = echarts.init(document.getElementById('chart1'));
						    chart1.setOption(option);
						}
						function showChartWindow() {
						    var win = mini.get("win1");
						    win.show();
						    buildChart();
						}
					showChartWindow();
				 }else if(cTableName == 'bar_chart'){
					 var barData = data[0];
					 console.log(barData,'柱状图数据');
					 var barXYData = barData.bar_list;
					 //横坐标
					 var barDistributionList = [];
					 barXYData.forEach((item,index)=>{
						 barDistributionList.push(item.column_name);
					 });
					 //纵坐标
					 var barYList = [];
					 barXYData.forEach((item,index)=>{
						 barYList.push(item.column_data);
					 });
					 var option = {
						        title: {
						            text: barData.bar_chart[0].bar_name,
						            subtext: barData.bar_chart[0].bar_subject,
						            x: 'center'
						        },
						        color: ['#3398DB'],
						        tooltip: {
						            trigger: 'axis',
						            axisPointer: {            // 坐标轴指示器，坐标轴触发有效
						                type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
						            }
						        },
						        grid: {
						            left: '3%',
						            right: '4%',
						            bottom: '3%',
						            containLabel: true
						        },
						        xAxis: [
						            {
						                type: 'category',
						                data: barDistributionList,
						                axisTick: {
						                    alignWithLabel: true
						                }
						            }
						        ],
						        yAxis: [
						            {
						                type: 'value'
						            }
						        ],
						        series: [
						            {
						                name: '直接访问',
						                type: 'bar',
						                barWidth: '60%',
						                data: barYList
						            }
						        ]
						    };

						    function buildChart2() {
						        var chart = echarts.init(document.getElementById('chartContainer'));
						        chart.setOption(option);
						    }
						    function showChartWindow2() {
						        var win = mini.get("win2");
						        win.show();
						        buildChart2();
						    }
						    showChartWindow2();
				 }
			 },
			 error: function(data){
				 console.log('失败');
			 }
		})   
	}else{
		mini.alert('请选择要查看图标的数据');
	}
}


